package cn.lixu.es;

import cn.lixu.utils.ESClientUtil;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;

/**
 * @author LiXu
 * @date 2022/08/18 0018 0:37:37
 */
public class ESSearch {
    public static void main(String[] args) {
        //1.获取连接
        TransportClient transportClient = ESClientUtil.getClient();
        //2.指定要查询的索引库
        SearchRequestBuilder pethome = transportClient.prepareSearch("pethome");
        //得到bool对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //设置must-match
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "我在源码");
        boolQueryBuilder.must(matchQueryBuilder);
        //设置fileter
        boolQueryBuilder.filter(QueryBuilders.termQuery("sex", 1))
                .filter(QueryBuilders.rangeQuery("age").gte(1).lte(12));
        pethome.setQuery(boolQueryBuilder);
        //每页条数
        pethome.setSize(2);
        //展示第几页数据
        pethome.setFrom(2);
        //排序规则
        pethome.addSort("age", SortOrder.DESC);

        for (SearchHit hit : pethome.get().getHits().getHits()) {

            System.out.println(hit.getSourceAsMap());
        }
        //关闭连接
        transportClient.close();

    }
}
